package com.esp.soccertutor.util;


import java.io.InputStream;
import java.io.OutputStream;
import java.security.Key;

import javax.crypto.Cipher;
import javax.crypto.CipherInputStream;
import javax.crypto.CipherOutputStream;
import javax.crypto.spec.SecretKeySpec;


public class SimpleProtector {
		
	private static Cipher ecipher;
	private static Cipher dcipher;
    
	private static final String ALGORITHM = "AES";
	public static String strKey = "0123456789012345";
	
	SimpleProtector() {
		try {

			Key key = generateKey();
			ecipher = Cipher.getInstance(ALGORITHM);
			dcipher = Cipher.getInstance(ALGORITHM);

			ecipher.init(Cipher.ENCRYPT_MODE, key);
			dcipher.init(Cipher.DECRYPT_MODE, key);

		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	 
	private static Key generateKey() throws Exception {
		
		
		byte[] keyBytes = strKey.getBytes();
		Key key = new SecretKeySpec(keyBytes, ALGORITHM);
		// SecretKeyFactory keyFactory =
		// SecretKeyFactory.getInstance(ALGORITHM);
		// key = keyFactory.generateSecret(new DESKeySpec(keyValue));
		return key;
	}
		    
		   
	// Buffer used to transport the bytes from one stream to another
	byte[] buf = new byte[1024];

	public boolean encrypt(InputStream in, OutputStream out) {
		
		try {
			// Bytes written to out will be encrypted
			out = new CipherOutputStream(out, ecipher);

			// Read in the cleartext bytes and write to out to encrypt
			int numRead = 0;
			while ((numRead = in.read(buf)) >= 0) {
				out.write(buf, 0, numRead);
			}
			out.close();
			return true;
		} catch (java.io.IOException e) {
			e.printStackTrace();
			return false;
		}
	}

	public void decrypt(InputStream in, OutputStream out) {
		try {
			// Bytes read from in will be decrypted
			in = new CipherInputStream(in, dcipher);

			// Read in the decrypted bytes and write the cleartext to out
			int numRead = 0;
			while ((numRead = in.read(buf)) >= 0) {
				out.write(buf, 0, numRead);
			}
			out.close();
		} catch (java.io.IOException e) {
			e.printStackTrace();
		}
	}

}
